import random
import json
from enum import Enum
from dataclasses import dataclass, asdict
from typing import List, Dict, Tuple, Optional
import time

class PoliticalSystem(Enum):
    NEUTRAL = "中立"
    SOCIALISM = "社会主义"
    CAPITALISM = "资本主义"
    FASCISM = "法西斯主义"

class ActionType(Enum):
    PEACE = "维持和平"
    AGGRESSION = "军事侵略"
    CULTURAL = "文化传播"
    ECONOMIC = "经济制裁"
    ALLIANCE = "结盟"

@dataclass
class Attributes:
    technology: float = 10.0
    education: float = 10.0
    military: float = 10.0
    economy: float = 10.0
    culture: float = 10.0
    
    def get_total_power(self) -> float:
        return (self.technology + self.education + self.military + 
                self.economy + self.culture) / 5

@dataclass
class Territory:
    name: str
    population: int
    resources: float
    development: float = 1.0
    
class Nation:
    def __init__(self, name: str, color: str, territories: List[Territory]):
        self.name = name
        self.color = color
        self.territories = territories
        self.attributes = Attributes()
        self.political_system = PoliticalSystem.NEUTRAL
        self.diplomatic_relations: Dict[str, float] = {}
        self.history: List[str] = []
        self.decisions_made: int = 0
        self.is_player = False
        
    def add_territory(self, territory: Territory):
        self.territories.append(territory)
        self.history.append(f"{self.name} 获得了 {territory.name}")
        
    def lose_territory(self, territory_name: str):
        self.territories = [t for t in self.territories if t.name != territory_name]
        self.history.append(f"{self.name} 失去了 {territory_name}")
        
    def develop_attributes(self):
        """发展国家属性"""
        tech_growth = random.uniform(0.5, 2.0)
        edu_growth = random.uniform(0.3, 1.5)
        mil_growth = random.uniform(0.5, 2.0)
        eco_growth = random.uniform(0.8, 2.5)
        cul_growth = random.uniform(0.2, 1.2)
        
        # 根据政治系统调整发展
        if self.political_system == PoliticalSystem.SOCIALISM:
            edu_growth *= 1.5
            eco_growth *= 0.8
            mil_growth *= 0.7
        elif self.political_system == PoliticalSystem.CAPITALISM:
            eco_growth *= 1.8
            tech_growth *= 1.3
            edu_growth *= 0.9
        elif self.political_system == PoliticalSystem.FASCISM:
            mil_growth *= 2.0
            tech_growth *= 1.2
            edu_growth *= 0.6
            cul_growth *= 0.5
            
        self.attributes.technology += tech_growth
        self.attributes.education += edu_growth
        self.attributes.military += mil_growth
        self.attributes.economy += eco_growth
        self.attributes.culture += cul_growth
        
    def check_political_evolution(self):
        """检查是否可以进入新的政治状态"""
        total_power = self.attributes.get_total_power()
        
        if total_power < 20:
            return PoliticalSystem.NEUTRAL
            
        # 根据属性特征决定政治倾向
        if self.attributes.military > self.attributes.economy * 1.5 and self.attributes.military > 25:
            return PoliticalSystem.FASCISM
        elif self.attributes.economy > self.attributes.military * 1.3 and self.attributes.economy > 25:
            return PoliticalSystem.CAPITALISM
        elif self.attributes.education > 20 and self.attributes.economy > 20:
            return PoliticalSystem.SOCIALISM
            
        return PoliticalSystem.NEUTRAL
        
    def get_ai_action(self, other_nations: List['Nation']) -> Tuple[ActionType, 'Nation']:
        """AI决策逻辑"""
        if not other_nations:
            return ActionType.PEACE, self
            
        # 根据政治系统决定行动
        if self.political_system == PoliticalSystem.FASCISM:
            # 法西斯主义倾向侵略
            weak_nations = [n for n in other_nations if n.attributes.military < self.attributes.military * 0.7]
            if weak_nations and random.random() < 0.7:
                target = random.choice(weak_nations)
                return ActionType.AGGRESSION, target
                
        elif self.political_system == PoliticalSystem.CAPITALISM:
            # 资本主义倾向经济行动
            if random.random() < 0.6:
                target = random.choice(other_nations)
                return ActionType.ECONOMIC, target
                
        elif self.political_system == PoliticalSystem.SOCIALISM:
            # 社会主义倾向和平
            if random.random() < 0.8:
                return ActionType.PEACE, self
                
        # 默认行为
        action_type = random.choice(list(ActionType))
        target = random.choice(other_nations) if action_type != ActionType.PEACE else self
        return action_type, target
        
    def execute_action(self, action_type: ActionType, target: 'Nation'):
        """执行行动"""
        if action_type == ActionType.AGGRESSION:
            success = self.attributes.military > target.attributes.military * random.uniform(0.8, 1.2)
            if success and target.territories:
                lost_territory = random.choice(target.territories)
                target.lose_territory(lost_territory.name)
                self.add_territory(lost_territory)
                self.history.append(f"{self.name} 成功侵略 {target.name}，获得 {lost_territory.name}")
                target.history.append(f"{target.name} 被 {self.name} 侵略，失去 {lost_territory.name}")
            else:
                self.history.append(f"{self.name} 侵略 {target.name} 失败")
                
        elif action_type == ActionType.CULTURAL:
            if target.territories:
                target.attributes.culture += random.uniform(1, 3)
                self.history.append(f"{self.name} 向 {target.name} 传播文化")
                
        elif action_type == ActionType.ECONOMIC:
            target.attributes.economy *= random.uniform(0.8, 0.95)
            self.attributes.economy += random.uniform(1, 2)
            self.history.append(f"{self.name} 对 {target.name} 实施经济制裁")
            
        elif action_type == ActionType.ALLIANCE:
            self.diplomatic_relations[target.name] = 100.0
            target.diplomatic_relations[self.name] = 100.0
            self.history.append(f"{self.name} 与 {target.name} 建立联盟")
            
    def get_total_population(self) -> int:
        return sum(t.population for t in self.territories)
        
    def get_total_resources(self) -> float:
        return sum(t.resources for t in self.territories)

class Game:
    def __init__(self):
        self.nations: List[Nation] = []
        self.turn = 0
        self.max_turns = 50
        self.game_over = False
        self.winner = None
        
    def initialize_game(self):
        """初始化游戏"""
        # 创建初始领土
        territory_a = Territory("红土平原", 1000000, 100)
        territory_b = Territory("蓝山高地", 800000, 80)
        territory_c = Territory("绿谷森林", 600000, 60)
        territory_d = Territory("金砂海岸", 1200000, 120)
        
        # 创建国家
        nation_a = Nation("红色共和国", "红色", [territory_a, territory_c])
        nation_b = Nation("蓝色联邦", "蓝色", [territory_b, territory_d])
        
        # 设置玩家控制
        nation_a.is_player = True
        
        self.nations = [nation_a, nation_b]
        
        # 初始化外交关系
        for nation in self.nations:
            for other in self.nations:
                if nation != other:
                    nation.diplomatic_relations[other.name] = 50.0
                    
    def player_decision_phase(self) -> Dict[str, any]:
        """玩家决策阶段"""
        player_nation = next(n for n in self.nations if n.is_player)
        other_nations = [n for n in self.nations if not n.is_player]
        
        print(f"\n=== {player_nation.name} 决策阶段 ===")
        print(f"当前政治制度: {player_nation.political_system.value}")
        print(f"综合国力: {player_nation.attributes.get_total_power():.1f}")
        print(f"领土数量: {len(player_nation.territories)}")
        print(f"总人口: {player_nation.get_total_population():,}")
        
        print("\n国家属性:")
        print(f"  科技: {player_nation.attributes.technology:.1f}")
        print(f"  教育: {player_nation.attributes.education:.1f}")
        print(f"  军事: {player_nation.attributes.military:.1f}")
        print(f"  经济: {player_nation.attributes.economy:.1f}")
        print(f"  文化: {player_nation.attributes.culture:.1f}")
        
        print(f"\n可执行的行动:")
        print("1. 发展军事")
        print("2. 发展科技")
        print("3. 发展教育")
        print("4. 发展经济")
        print("5. 发展文化")
        print("6. 军事侵略")
        print("7. 文化传播")
        print("8. 经济制裁")
        
        if other_nations:
            print("9. 建立联盟")
            
        choice = input("请选择行动 (1-9): ").strip()
        
        decision = {
            'nation': player_nation,
            'choice': choice,
            'target': None
        }
        
        if choice in ['6', '7', '8', '9'] and other_nations:
            print("选择目标国家:")
            for i, nation in enumerate(other_nations, 1):
                print(f"{i}. {nation.name}")
            target_choice = input("选择目标: ").strip()
            if target_choice.isdigit() and 1 <= int(target_choice) <= len(other_nations):
                decision['target'] = other_nations[int(target_choice) - 1]
                
        return decision
        
    def execute_player_decision(self, decision: Dict[str, any]):
        """执行玩家决策"""
        player_nation = decision['nation']
        choice = decision['choice']
        target = decision['target']
        
        if choice == '1':
            player_nation.attributes.military += random.uniform(3, 6)
            player_nation.history.append("决定发展军事")
        elif choice == '2':
            player_nation.attributes.technology += random.uniform(3, 6)
            player_nation.history.append("决定发展科技")
        elif choice == '3':
            player_nation.attributes.education += random.uniform(3, 6)
            player_nation.history.append("决定发展教育")
        elif choice == '4':
            player_nation.attributes.economy += random.uniform(3, 6)
            player_nation.history.append("决定发展经济")
        elif choice == '5':
            player_nation.attributes.culture += random.uniform(3, 6)
            player_nation.history.append("决定发展文化")
        elif choice == '6' and target:
            player_nation.execute_action(ActionType.AGGRESSION, target)
        elif choice == '7' and target:
            player_nation.execute_action(ActionType.CULTURAL, target)
        elif choice == '8' and target:
            player_nation.execute_action(ActionType.ECONOMIC, target)
        elif choice == '9' and target:
            player_nation.execute_action(ActionType.ALLIANCE, target)
            
        player_nation.decisions_made += 1
        
    def ai_turn(self):
        """AI回合"""
        ai_nations = [n for n in self.nations if not n.is_player]
        
        for ai_nation in ai_nations:
            other_nations = [n for n in self.nations if n != ai_nation]
            action_type, target = ai_nation.get_ai_action(other_nations)
            ai_nation.execute_action(action_type, target)
            
    def update_political_systems(self):
        """更新政治制度"""
        for nation in self.nations:
            new_system = nation.check_political_evolution()
            if new_system != nation.political_system:
                old_system = nation.political_system.value
                nation.political_system = new_system
                nation.history.append(f"{nation.name} 从 {old_system} 转变为 {new_system.value}")
                print(f"\n{nation.name} 转变为 {new_system.value}!")
                
    def check_victory_conditions(self):
        """检查胜利条件"""
        for nation in self.nations:
            if len(nation.territories) == 0:
                self.nations.remove(nation)
                print(f"\n{nation.name} 灭亡了!")
                
        if len(self.nations) == 1:
            self.winner = self.nations[0]
            self.game_over = True
            return
            
        # 检查是否达到回合上限
        if self.turn >= self.max_turns:
            self.game_over = True
            # 根据综合国力决定胜者
            self.winner = max(self.nations, key=lambda n: n.attributes.get_total_power())
            
    def display_status(self):
        """显示游戏状态"""
        print(f"\n{'='*50}")
        print(f"回合 {self.turn}/{self.max_turns}")
        print(f"{'='*50}")
        
        for nation in self.nations:
            print(f"\n{nation.name} ({nation.color})")
            print(f"  政治制度: {nation.political_system.value}")
            print(f"  综合国力: {nation.attributes.get_total_power():.1f}")
            print(f"  领土: {len(nation.territories)} 个")
            print(f"  人口: {nation.get_total_population():,}")
            print(f"  {'玩家' if nation.is_player else 'AI'}")
            
    def run(self):
        """运行游戏"""
        print("欢迎来到国家政治模拟游戏!")
        print("你将控制一个国家，通过发展各项属性来影响国家的政治走向和国际地位。")
        print("不同的政治制度将带来不同的行为模式和发展路径。")
        print("目标：在50回合内成为最后的胜利者!")
        
        self.initialize_game()
        
        while not self.game_over:
            self.turn += 1
            
            # 显示状态
            self.display_status()
            
            # 玩家决策阶段
            if any(n.is_player for n in self.nations):
                decision = self.player_decision_phase()
                self.execute_player_decision(decision)
                
            # AI回合
            self.ai_turn()
            
            # 发展阶段
            for nation in self.nations:
                nation.develop_attributes()
                
            # 检查政治制度变化
            self.update_political_systems()
            
            # 检查胜利条件
            self.check_victory_conditions()
            
            if not self.game_over:
                input("\n按回车键继续...")
                
        # 游戏结束
        print(f"\n游戏结束!")
        if self.winner:
            print(f"胜利者: {self.winner.name}")
            print(f"最终政治制度: {self.winner.political_system.value}")
            print(f"最终综合国力: {self.winner.attributes.get_total_power():.1f}")
            
        # 显示历史记录
        print(f"\n历史记录:")
        for nation in self.nations:
            print(f"\n{nation.name}:")
            for event in nation.history[-5:]:  # 显示最后5个事件
                print(f"  - {event}")

if __name__ == "__main__":
    game = Game()
    game.run()